﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;

namespace project
{
    public class DBHelper
    {
        public static string ConnString= "Data Source=.;Initial Catalog=CAR;Integrated Security=True";
        /// <summary>
        /// 创建连接对象
        /// </summary>
        public static SqlConnection Conn = null;
        /// <summary>
        /// 创建连接
        /// </summary>
        public static void InitConnection()
        {
            //不存在
            if (Conn==null)
            {
                Conn = new SqlConnection(ConnString);
            }
            //关闭
            if (Conn.State==ConnectionState.Closed)
            {
                Conn.Open();
            }
            //中断
            if (Conn.State==ConnectionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }
        //获得DataTable
        public static DataTable GetTable(string sql)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql,Conn);
            DataTable dt = new DataTable();
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            dap.Fill(dt);
            return dt;
        }
        //增加，删除，修改
        public static int ExecuteNonQuery(string sql)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql,Conn);
            int result= cmd.ExecuteNonQuery();
            Conn.Close();
            return result;
        } 
    }
}
